package com.duke.payphone.sell;

import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.duke.payphone.Global;
import com.duke.payphone.LoginActivity;
import com.duke.payphone.R;
import com.duke.payphone.ServerPortal;
import com.duke.payphone.factory.MapFactory;


/**
 * allows user to enter new product to sell (enter product name, price, etc)
 * 
 * user clicks Post:
 * app checks that the new product data is valid, and sends the data to the
 * server
 * server creates a "new transaction"
 * IMPORTANT: once the user clicks POST, the transaction cannot be removed (it
 * can be timed out)
 * 
 * server returns valid (+ image of barcode), app loads "SellQR" activity (app
 * saves image in globalvars)
 * 
 * server returns invalid, toast = "new product invalid", stay in this activity
 * 
 * 
 * 
 * buttons: Post, Cancel (back to ROOT)
 * 
 * @author Michael
 * 
 */
public class SellNewActivity extends Activity {
    private Global globalvars;

    private EditText name;
    private EditText price;

    private String productnameStr;
    private String priceStr;

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sell_new);

        globalvars = (Global) getApplicationContext();

        name = (EditText) findViewById(R.id.et_name);
        price = (EditText) findViewById(R.id.et_price);

    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        // getMenuInflater().inflate(R.menu.activity_sell_new, menu);
        // return true;
        return false;
    }

    public void executeCancel (View v) {
        finish();
    }

    /**
     * @param v
     */
    public void executePost (View v) {
        // grab data..
        updateData();

        // check validity
        if (checkData()) {

            // send to server
            Map<String, Serializable> response = ServerPortal.contactServer(prepareTransmitMap());

            // wait for reply
            if (response.containsKey("server") && response.get("server").equals("valid")) {

                if (response.containsKey("session") && response.get("session").equals("valid")) {

                    if (response.containsKey("result") && response.get("result").equals("valid")) {
                        onSellNewValid(response);
                    }
                    else {
                        onSellNewInvalid(response);
                    }
                }
                else {
                    onSessionInvalid();
                }
            }
            else {
                onServerInvalid();
            }
        }
    }

    /**
     * Rereads the data from text fields
     */
    private void updateData () {
        productnameStr = name.getText().toString();
        priceStr = price.getText().toString();
    }

    /**
     * returns a map
     * 
     * @return
     */
    private Map<String, Serializable> prepareTransmitMap () {
        Map<String, Serializable> request = MapFactory.createTransmitMap("sellnew");
        request.put("productname", productnameStr);
        request.put("price", priceStr);
        request.put("date",
                    java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance()
                                                                              .getTime()));

        return request;
    }

    private boolean checkData () {
        // verify data is correct
        if (productnameStr.isEmpty() || priceStr.isEmpty()) {
            // if incorrect, toast: [how to correct the data]
            Toast.makeText(globalvars, "All fields required.", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    /**
     * @param response
     */
    private void onSellNewValid (Map<String, Serializable> response) {

        // TODO grab image and pass to next activity using intent
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.testcode);
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
//        byte[] b = baos.toByteArray();
        byte[] b = (byte[]) response.get("qrcode");

        Toast.makeText(globalvars, "Post successful.", Toast.LENGTH_SHORT).show();

        // show qr code
        Intent toSellQR = new Intent(this, SellQRActivity.class);
        toSellQR.putExtra("qrcode", b);
        startActivity(toSellQR);
        finish();
    }

    /**
     * @param response
     */
    private void onSellNewInvalid (Map<String, Serializable> response) {
        Toast.makeText(globalvars, "Post unsuccessful. Please try again.", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * If server has timed out
     */
    private void onServerInvalid () {
        // toast: server error, please verify server connection and retry
        // request
        Toast.makeText(globalvars, "Server/network error. Please retry.", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * If session has timed out
     */
    private void onSessionInvalid () {
        // reset the sessionID to null
        Global.sessionid = "";

        // toast: current session has timed out
        Toast.makeText(globalvars, "Current session has timed out.", Toast.LENGTH_SHORT).show();

        // go back to the login screen
        Intent toLogin = new Intent(this, LoginActivity.class);
        toLogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(toLogin);
        finish();
    }

}
